//
//  SD78Mp3Cell.m
//  DoorBell
//
//  Created by eques on 2024/2/26.
//  Copyright © 2024 eques. All rights reserved.
//

#import "CatVoiceCell.h"
#import <AVFoundation/AVFoundation.h>




@interface CatVoiceCell()<AVAudioPlayerDelegate>
@property(nonatomic,strong)UIView   *contrainView;
@property(nonatomic,strong)UILabel  *titelLabel;
@property(nonatomic,strong)UIButton *playButton;
@property(nonatomic,strong)UILabel  *timelabel;

@property(nonatomic,strong)AVAudioSession *audioSession;
@property(nonatomic,strong)AVAudioPlayer *audioPlayer; //播放器
@property(nonatomic,strong)NSTimer* timer;
@property(nonatomic,assign)int playTime;
@property(nonatomic,assign)int playDuration;

@end

@implementation CatVoiceCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

}


- (UIView*)contrainView
{
    if (!_contrainView) {
         _contrainView = [[UIView alloc] init];
         _contrainView.layer.cornerRadius = 8;
         _contrainView.layer.borderWidth = 1.0;
         _contrainView.layer.borderColor = [HexChangeRGB colorWithHexString:@"#E1E1E1"].CGColor;
         _contrainView.layer.masksToBounds = YES;
        [self.contentView addSubview:_contrainView];
        [_contrainView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(60);
            make.centerY.equalTo(self.contentView.mas_centerY);
            make.left.equalTo(self.contentView.mas_left).offset(14);
            make.right.equalTo(self.contentView.mas_right).offset(-14);
        }];
        
    }
     return _contrainView;
}

- (UIImageView*)selectedImage
{
    // 勾选框
    if (!_selectedImage) {
         _selectedImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_check_alpha"]];
        [self.contrainView addSubview:_selectedImage];
        [_selectedImage mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.contrainView.mas_centerY);
            make.right.equalTo(self.contrainView.mas_right).offset(-20);
            make.width.mas_equalTo(20);
            make.height.mas_equalTo(20);
        }];
    }
    
    return _selectedImage;
}



- (UIButton*)playButton
{
    if (!_playButton) {
         _playButton = [[UIButton alloc] init];
        [_playButton setImage:[UIImage imageNamed:@"sd78_voice_play"] forState:UIControlStateNormal];
        [self.contrainView addSubview:_playButton];
        [_playButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(24);
            make.height.mas_equalTo(24);
            make.top.equalTo(self.contrainView.mas_top).offset(14);
            if (self.model.cell_type) {
                
                make.left.equalTo(self.titelLabel.mas_right).offset(10);
            }else{
                make.top.equalTo(self.contrainView.mas_top).offset(14);
                make.right.equalTo(self.contrainView.mas_right).offset(-14);
            }
        }];
        [_playButton addTarget:self action:@selector(playButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
     return _playButton;
}
#pragma  mark 点击播放
- (void)playButtonClick:(UIButton *)sender{
    
    if(self.isRecording){
        [SVProgressHUD showErrorWithStatus:@"正在录音，请录完再播放！" duration:1.5];
         return;
    }
    
    self.isPlaying = YES;
    if ([self.audioPlayer isPlaying]) {
        [self.audioPlayer pause];
        [self.playButton setImage:[UIImage imageNamed:@"sd78_voice_play"] forState:UIControlStateNormal];
    }else{
        
        if(self.playTime < self.playDuration && self.playTime >0){
            
            [self.audioPlayer play];
            [self.playButton setImage:[UIImage imageNamed:@"sd78_voice_pause"] forState:UIControlStateNormal];
            
        }else{
            if(self.playBlock){
               self.playBlock(YES);
            }
            
            [self.playButton setImage:[UIImage imageNamed:@"sd78_voice_pause"] forState:UIControlStateNormal];
            
            NSString *pathPrefix = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
            NSString *saveTo = [[pathPrefix stringByAppendingPathComponent:@"MP3"] stringByAppendingPathComponent:self.bid];
            NSString *imagePath = [saveTo stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",self.model.file_name]];
         
           
            
            if ([self.model.file_name_value isEqualToString:@"cat_feed"]) {
                NSString *filePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@.mp3",self.model.file_name] ofType:nil];
                [self playMp3:filePath];
                return;
            }
            if(self.model.cell_type == 1){
                 NSString *imagePath = [saveTo stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.pcm",self.model.file_name]];
                [self playMp3:imagePath];
                 return;
            }
            
            [self playMp3:imagePath];
        }
    }
    
}

- (void)stopPlay
{
    
    if(self.playBlock){
       self.playBlock(NO);
    }
    
    self.playTime = 0;
    self.playDuration = 0;
   [self.audioPlayer stop];
    self.audioPlayer = nil;
   [[AVAudioSession sharedInstance] setActive:NO error:nil];
   
   [self.playButton setImage:[UIImage imageNamed:@"sd78_voice_play"] forState:UIControlStateNormal];
   
   [self.timelabel setText:self.model.durtation_str];
   [self.timer invalidate];
    self.timer = nil;
    self.isPlaying = NO;
}


- (UILabel*)timelabel
{
    if (!_timelabel) {
          _timelabel = [[UILabel alloc]init];
         [self.contrainView addSubview:_timelabel];
          _timelabel.textColor = [HexChangeRGB colorWithHexString:@"#999999"];
          _timelabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:10.0];
          _timelabel.numberOfLines = 0;
         [_timelabel sizeToFit];
         [_timelabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.playButton.mas_centerX);
            make.top.equalTo(self.playButton.mas_bottom);
         }];
    }
    return _timelabel;
}

- (UILabel*)titelLabel
{
     if (!_titelLabel) {
          _titelLabel = [[UILabel alloc]init];
         [self.contrainView addSubview:_titelLabel];
          _titelLabel.textColor = [HexChangeRGB colorWithHexString:@"#666666"];
          _titelLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16.0];
          _titelLabel.numberOfLines = 0;
         [_titelLabel sizeToFit];
         [_titelLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.contrainView.mas_centerY);
            make.left.equalTo(self.contrainView.mas_left).offset(12);
         }];
    }
    return _titelLabel;
}

- (void)setModel:(CatVoiceModel *)model
{
     _model = model;
     self.contrainView.backgroundColor = [UIColor whiteColor];
     self.titelLabel.text =  model.file_name;
    if (model.durtation_str.length > 0) {
        [self.playButton setImage:[UIImage imageNamed:@"sd78_voice_play"] forState:UIControlStateNormal];
         self.timelabel.text = model.durtation_str;
    }else{
        if (_playButton) {
            [_playButton removeFromSuperview];
            _playButton = nil;
        }
        if (_timelabel) {
            [_timelabel removeFromSuperview];
            _timelabel = nil;
        }
    }
    
    if(_model.cell_type == 1 && ![model.file_name isEqualToString:NSLocalizedString(@"使用默认语音",nil)]) {
       self.titelLabel.text =  NSLocalizedString(@"自定义语音",nil);
    }
}



- (void)playMp3:(NSString*)path
{
     self.audioSession = [AVAudioSession sharedInstance];
    [self.audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [self.audioSession setActive:YES error:nil];
  
     NSError *error;
     self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
    
     self.audioPlayer.delegate = self;
    [self.audioPlayer prepareToPlay];
     self.audioPlayer.volume = 1;
    [self.audioPlayer play];
    
     self.playDuration = (int)self.audioPlayer.duration;
     NSLog(@"音频时长为：%i",self.playDuration);
    if (self.model.durtation == 0) {
        self.timelabel.text = [NSString stringWithFormat:@"00:%02d",self.playDuration];
    }
     self.playTime = 0;
    [self audioPlayTimeStart];
}


- (void)audioPlayTimeStart {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(playTimeTick) userInfo:nil repeats:YES];
}

- (void)playTimeTick {
    
    if (self.playDuration == self.playTime) {
         self.playTime = 0;
        [self.audioPlayer stop];
         self.audioPlayer = nil;
        [[AVAudioSession sharedInstance] setActive:NO error:nil];
        
        [self.playButton setImage:[UIImage imageNamed:@"sd78_voice_play"] forState:UIControlStateNormal];
        
        [self.timelabel setText:self.model.durtation_str];
        [self.timer invalidate];
         self.timer = nil;
         self.isPlaying = NO;
         if(self.playBlock){
           self.playBlock(NO);
         }
        return;
    }
    if (![self.audioPlayer isPlaying]) {
        return;
    }
     self.playTime += 1;
    [self updateAudioPlayTime];
}

- (void)updateAudioPlayTime {
     int minute = self.playTime/60.0;
     int second = self.playTime-minute*60;
    [self.timelabel setText:[NSString stringWithFormat:@"%02d:%02d",minute,second]];
}

//AVAudioRecorderDelegate方法
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    
    self.playTime = 0;
   [self.audioPlayer stop];
    self.audioPlayer = nil;
   [[AVAudioSession sharedInstance] setActive:NO error:nil];
   
   [self.playButton setImage:[UIImage imageNamed:@"sd78_voice_play"] forState:UIControlStateNormal];
   
   [self.timelabel setText:self.model.durtation_str];
   [self.timer invalidate];
    self.timer = nil;
    self.isPlaying = NO;
 
}

@end
